<!DOCTYPE html>
<html>
<head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
    <title>Batch Create Instance</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

</head>
<body>
<div class="container">
    <div class="section">
        <div class="row">
            <div class="col m10 push-m2" id="create-panel">
              <div class="row">
                <div class="input-field" id="rule-options">
                  <div class="col m2">
                    <label id="rule-label"></label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="count-label"></label>
                </div>
                <div class="range-field col m4">
                  <input id="guest-count" type="range">
                </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="prefix-label"></label>
                </div>
                <div class="input-field col m3">
                  <input id="prefix-name" type="text">
                </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="pool-label"></label>
                </div>
                <div class="input-field col m3">
                  <select name="pool" id="pool-options">
                  </select>
                </div>
              </div>
              <div class="row">
                <div class="input-field" id="core-options">
                  <div class="col m2">
                    <label id="core-label"></label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="input-field" id="memory-options">
                  <div class="col m2">
                    <label id="memory-label"></label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="input-field">
                  <div class="col m2">
                    <label id="version-label"></label>
                  </div>
                  <div class="col m3">
                    <select name="system-version" id="version-options" onchange="onSystemChanged()">
                    </select>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="input-field">
                  <div class="col m2">
                    <label id="system-disk-label"></label>
                  </div>
                  <div class="col m4 range-field">
                    <input type="range" id="system-disk" onchange="onSystemDiskChanged()">
                  </div>
                  <div class="col m2">
                    <label>
                      <span id="system-disk-tip"></span>
                    </label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="input-field">
                  <div class="col m2">
                    <label id="data-disk-label"></label>
                  </div>
                  <div class="col m4 range-field">
                    <input type="range" id="data-disk" onchange="onDataDiskChanged()">
                  </div>
                  <div class="col m2">
                    <label>
                      <span id="data-disk-tip"></span>
                    </label>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="auto-start-label"></label>
                </div>
                <div class="switch">
                  <label id="auto-start-switch">
                  </label>
                </div>
              </div>
              <div class="row">
                <div class="col m2">
                  <label id="system-image-label"></label>
                </div>
                <div class="input-field col m3">
                  <select name="from_image" id="image-options" onchange="onImageChanged()">
                    <option value="" id="blank-system-label"></option>
                  </select>
                </div>
              </div>
              <!-- CPU Priority -->
              <div class="row">
                  <div class="input-field" id="priority-options">
                      <div class="col m2">
                          <label id="priority-label"></label>
                      </div>
                  </div>
              </div>
              <!-- IOPS -->
              <div class="row">
                  <div class="input-field">
                      <div class="col m2">
                          <label id="iops-label"></label>
                      </div>
                      <div class="col m4 range-field">
                        <input type="range" id="iops" onchange="onIOPSChanged()">
                      </div>
                      <div class="col m2">
                        <label>
                          <span id="iops-tip"></span>
                        </label>
                      </div>
                  </div>
              </div>
              <!-- inbound -->
              <div class="row">
                  <div class="input-field">
                      <div class="col m2">
                          <label id="inbound-label"></label>
                      </div>
                      <div class="col m3 range-field">
                        <input type="range" id="inbound" onchange="onInboundChanged()">
                      </div>
                      <div class="col m2">
                        <label>
                          <span id="inbound-tip"></span>
                        </label>
                      </div>
                  </div>
              </div>
              <!-- outbound -->
              <div class="row">
                  <div class="input-field">
                      <div class="col m2">
                          <label id="outbound-label"></label>
                      </div>
                      <div class="col m3 range-field">
                        <input type="range" id="outbound" onchange="onOutboundChanged()">
                      </div>
                      <div class="col m2">
                        <label>
                          <span id="outbound-tip"></span>
                        </label>
                      </div>
                  </div>
              </div>
              <div class="modal" id="confirm_modal">
                <!--hide model -->
                <div class="modal-content">
                  <h4>Confirm Create Instance</h4>
                  <p>Create new instance using following configures</p>
                </div>
                <div class="modal-footer">
                  <a href="#" class="modal-close waves-effect waves-green btn-flat"></a>
                  <a href="#" class="modal-close waves-effect waves-green btn-flat" onclick="submitCreateRequest()"></a>
                </div>
              </div>

            </div>

        </div>
    </div>
    <div class="divider"></div>
    <div class="section">
        <div class="row">
            <div class="col m2">
                <a class="waves-effect waves-light blue-grey lighten-2 btn" onclick="window.history.back()" id="back-caption"><i
                        class="material-icons left">chevron_left</i></a>
            </div>
            <div class="col m2 right" id="button">
                <button class="waves-effect waves-light blue-grey lighten-2 btn modal-trigger"
                        data-target="confirm_modal" id="create-caption">
                    <i class="material-icons right">add</i>
                </button>
            </div>
        </div>
    </div>
</div>

<!--JavaScript at end of body for optimized loading-->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<script type="text/javascript" src="js/nano.js"></script>
<script>
N.ValidateSession();
var texts = N.GetTexts();
var versions = new Map(
  [
    ["centos7", {Name: 'CentOS 7 or Later', System: 'linux', Enable: true}],
    ["centos6", {Name: 'CentOS 6', System: 'linux', Enable: true}],
    ["win2012", {Name: 'Windows Server 2012', System: 'windows', Enable: true}],
    ["legacy", {Name: 'Legacy system', System: 'linux', Enable: true}],
    ["general", {Name: 'Other General System', System: 'linux', Enable: true}],
  ]
);

M.AutoInit();

function mapValue(sizeInMB){
  var size = sizeInMB * 1048576;
  if(sizeInMB >= 1024){
    var sizeInGB = sizeInMB / 1024;
    return {Label: sizeInGB + 'G', Value: size};
  }else{
    return {Label: sizeInMB + 'M', Value: size};
  }
}

function onSystemDiskChanged(){
  var currentValue = $('#system-disk').val();
  $('#system-disk-tip').text(currentValue + ' GiB');
}

function onDataDiskChanged(){
  var currentValue = $('#data-disk').val();
  if(0 == currentValue){
    if(N.IsChinese()){
      $('#data-disk-tip').text('不使用');
    }else{
      $('#data-disk-tip').text("Don't use");
    }
  }else {
    $('#data-disk-tip').text(currentValue + ' GiB');
  }
}


function onIOPSChanged(){
  var currentValue = $('#iops').val();
  if(0 == currentValue){
    if(N.IsChinese()){
      $('#iops-tip').text('无限制');
    }else{
      $('#iops-tip').text("No limit");
    }
  }else {
    $('#iops-tip').text(currentValue + ' IOPS');
  }
}

function onInboundChanged(){
  var currentValue = $('#inbound').val();
  if(0 == currentValue){
    if(N.IsChinese()){
      $('#inbound-tip').text('无限制');
    }else{
      $('#inbound-tip').text("No limit");
    }
  }else {
    $('#inbound-tip').text(currentValue + ' Mbit/s');
  }
}

function onOutboundChanged(){
  var currentValue = $('#outbound').val();
  if(0 == currentValue){
    if(N.IsChinese()){
      $('#outbound-tip').text('无限制');
    }else{
      $('#outbound-tip').text("No limit");
    }
  }else {
    $('#outbound-tip').text(currentValue + ' Mbit/s');
  }
}

function loadOptions(){

  $('#back-caption').append(texts.get(N.TagBack));
  $('#create-caption').prepend(texts.get(N.TagCreate));
  $('.modal-footer > a:first-child').text(texts.get(N.TagCancel));
  $('.modal-footer > a:last-child').text(texts.get(N.TagConfirm));

  if(N.IsChinese()){
    $('#rule-label').text('实例名规则');
    $('#rule-options').append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('order').prop('checked', true)
      ).append(
        $('<span>').text('顺序递增')
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('MAC').prop('disabled', true)
      ).append(
        $('<span>').text('按MAC地址')
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('address').prop('disabled', true)
      ).append(
        $('<span>').text('按实例地址')
      )
    );
    $('#count-label').text('实例数量');
    $('#prefix-label').text('实例名前缀');
    $('#priority-label').text('CPU优先级');
    $('#iops-label').text('IOPS');
    $('#inbound-label').text('下行带宽');
    $('#outbound-label').text('上行带宽');
  }else{
    $('#rule-label').text('Rule of Instance name');
    $('#rule-options').append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('order').prop('checked', true)
      ).append(
        $('<span>').text('By Order')
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('MAC').prop('disabled', true)
      ).append(
        $('<span>').text('By MAC')
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<input>').addClass('with-gap').attr('name', 'name_rule').attr('type', 'radio').val('address').prop('disabled', true)
      ).append(
        $('<span>').text('By Address')
      )
    );
    $('#count-label').text('Instance Count');
    $('#prefix-label').text('Name Prefix');
    $('#priority-label').text('CPU Priority');
    $('#iops-label').text('IOPS');
    $('#inbound-label').text('Inbound Bandwidth');
    $('#outbound-label').text('Outbound Bandwidth');
  }


  $('#pool-label').text(texts.get(N.TagComputePool));
  $('#core-label').text(texts.get(N.TagCore));
  $('#memory-label').text(texts.get(N.TagMemory));
  $('#system-label').text(texts.get(N.TagSystem));
  $('#system-disk-label').text(texts.get(N.TagSystemDisk));
  $('#system-image-label').text(texts.get(N.TagSystemImage));
  $('#blank-system-label').text(texts.get(N.TagBlankSystem));
  $('#data-disk-label').text(texts.get(N.TagDataDisk));
  $('#auto-start-label').text(texts.get(N.TagAutoStart));

  $('#auto-start-switch').append(
    $('<label>').append(texts.get(N.TagDisable)).append(
      $('<input>').attr('type', 'checkbox').attr('name', 'auto_start').attr('id', 'auto_start').prop('checked', true)
    ).append(
      $('<span>').addClass('lever')
    ).append(texts.get(N.TagEnable))
  )

  $('#guest-count').attr('min', '1').attr('max', '20').val(1);
  //cores
  {
    var coreData = [1, 2, 4, 8];
    var option = $('#core-options');
    coreData.forEach((core)=>{
      var input = $('<input>').addClass('with-gap').attr('name', 'cores').attr('type', 'radio').val(core);
      if(1 == core){
        input.prop('checked', true);
      }
      option.append(
        $('<div>').addClass('col m1').append(
          $('<label>').append(
            input
          ).append(
            $('<span>').text(core)
          )
        )
      );
    });
  }
  {
    //memory options
    var memoryData = [512, 1024, 2*1024, 4*1024, 8*1024];
    var option = $('#memory-options');
    memoryData.forEach((memory)=>{
      var tag = mapValue(memory);
      var input = $('<input>').addClass('with-gap').attr('name', 'memory').attr('type', 'radio').val(tag.Value);
      if(1024 == memory){
        input.prop('checked', true);
      }
      option.append(
        $('<div>').addClass('col m1').append(
          $('<label>').append(
            input
          ).append(
            $('<span>').text(tag.Label)
          )
        )
      );
    });
  }

  {
    //system disk
    const minSize = 5, maxSize = 60, moveStep = 1, defaultSize = minSize;
    $('#system-disk').attr('min', minSize).attr('max', maxSize)
      .attr('value', defaultSize).attr('step', moveStep);
    onSystemDiskChanged();
  }
  {
    //data disk
    const minSize = 0, maxSize = 20, moveStep = 2, defaultSize = minSize;
    $('#data-disk').attr('min', minSize).attr('max', maxSize)
      .attr('value', defaultSize).attr('step', moveStep);
    onDataDiskChanged();
  }


    {
      //priority
      var priorityData;
      if(N.IsChinese()){
        priorityData = [
          ["high", "高", false],
          ["medium", "中", true],
          ["low", "低", false]
        ];
      }else{
        priorityData = [
          ["high", "High", false],
          ["medium", "Medium", true],
          ["low", "Low", false]
        ];
      }
      var option = $('#priority-options');
      priorityData.forEach((data)=>{
        var value = data[0];
        var label = data[1];
        var isChecked = data[2];
        var input = $('<input>').addClass('with-gap').attr('name', 'priority').attr('type', 'radio').val(value);
        if(isChecked){
          input.prop('checked', true);
        }
        option.append(
          $('<div>').addClass('col m2').append(
            $('<label>').append(
              input
            ).append(
              $('<span>').text(label)
            )
          )
        );
      });
    }
    {
      //iops
      const minSize = 0, maxSize = 2000, moveStep = 10, defaultSize = minSize;
      $('#iops').attr('min', minSize).attr('max', maxSize)
        .attr('value', defaultSize).attr('step', moveStep);
      onIOPSChanged();
    }
    {
      //inbound
      const minSize = 0, maxSize = 20, moveStep = 1, defaultSize = minSize;
      $('#inbound').attr('min', minSize).attr('max', maxSize)
        .attr('value', defaultSize).attr('step', moveStep);
      onInboundChanged();
    }
    {
      //outsbound
      const minSize = 0, maxSize = 20, moveStep = 1, defaultSize = minSize;
      $('#outbound').attr('min', minSize).attr('max', maxSize)
        .attr('value', defaultSize).attr('step', moveStep);
      onOutboundChanged();
    }

  $.getJSON("/compute_pools/", function(result){
    if (0 != result['error_code']) {
        M.toast({html: 'query compute pools fail:' + result['message']});
        return;
    }
    if (!result['data']){
      M.toast({html: 'no compute pool available'});
      return;
    }
    result['data'].forEach((pool) =>{
      var currentName = pool['name'];
      var option = $('<option>').attr('value', currentName).text(currentName);
      if (poolName&&poolName == currentName){
        option.prop('selected', true);
      }
      $('#pool-options').append(
        option
      )
    });
    M.FormSelect.init($('#pool-options'));

    $('#version-label').text(texts.get(N.TagSystemVersion));
    var versionOptions = $('#version-options');
    versions.forEach((info, version) =>{
      var option = $('<option>').attr('value', version).text(info.Name);
      if (!info.Enable){
        option.prop('disabled', true);
      }
      versionOptions.append(option);
    });

    M.FormSelect.init($('#version-options'));
  });
  var queryImage = '/disk_image_search/?session=' + N.GetSessionID();
  $.getJSON(queryImage, function(result){
    if (0 != result['error_code']) {
        M.toast({html: 'query disk images fail:' + result['message']});
        return;
    }
    if (0 == result['data'].length){
        $('#image-options').attr('disabled', 'disabled');
        return;
    }
    result['data'].forEach((image) =>{
      $('#image-options').append(
        $('<option>').attr('value', image['id']).text(image['name'])
      )
    });
    M.FormSelect.init($('#image-options'));
  });
}

function initialForm(){
  loadOptions();
  M.Modal.init($('.modal'), {});
}

function finishCreate(){
  // $('#create-result').text('success');
  var finishPage;
  if (originURL){
    finishPage = "instance_list.html";
  }else{
    finishPage = 'instances.html';
  }
  if (poolName){
    finishPage += "?pool=" + poolName;
  }
  $('#button').append(
    $('<a>').attr('href', finishPage).append(
      $('<button>').addClass('waves-effect waves-light blue-grey lighten-2 btn').text(texts.get(N.TagFinish)).prepend(
        $('<i>').addClass('material-icons').text('check')
      )
    )
  );
}

var batchID;

function initialProgressList(statusList){
  var list = $('<table>').addClass('striped');
  statusList.forEach((status)=>{
    var row = $('<tr>');
    var instanceName = status['name'];
    row.append(
      $('<td>').text(instanceName)
    );
    var statusCell = $('<td>').attr('id', instanceName + '-status');
    if ('created' == status['status']){
      //success
      statusCell.text('success');
    }else if ('fail' == status['status']){
      //fail
      statusCell.text(status['error'])
    }else{
      //creating
      var progress = status['progress'] + '%';
      statusCell.append(
        $('<div>').addClass('center').append(
          $('<span>').text('Creating... ' + progress).attr('id', instanceName + '-hint')
        )
      ).append(
        $('<div>').addClass('progress').append(
          $('<div>').addClass('determinate').width(progress).attr('id', instanceName + '-progress')
        )
      );
    }
    list.append(
      row.append(statusCell)
    );
  });
  $('#create-result').append(list);
}

function updateProgressList(statusList){
  statusList.forEach((status)=>{
    var instanceName = status['name'];
    var statusCell = $('#' + instanceName + '-status');
    if ('created' == status['status']){
      //success
      statusCell.empty().text('success');
    }else if ('fail' == status['status']){
      //fail
      statusCell.empty().text(status['error'])
    }else{
      //creating
      var progress = status['progress'] + '%';
      $('#' + instanceName + '-hint').text('Creating... ' + progress);
      $('#' + instanceName + '-progress').width(progress);
    }
  });
}

function checkResult(){
  $.ajax({
    url: '/batch/create_guest/' + batchID,
    method: "GET",
    dataType: "json",
    statusCode:{
      202: function(result){
        updateProgressList(result['data']);
        setTimeout(checkResult, 1000);
      },
      200: function(result){
        if (0 != result['error_code']) {
          $('#create-result').text(result['message']);
          //fail
          return;
        }
        updateProgressList(result['data']);
        finishCreate();
      }
    }
  });
}

function beginCheckProgress(){
  $.ajax({
    url: '/batch/create_guest/' + batchID,
    method: "GET",
    dataType: "json",
    statusCode:{
      202: function(result){
        //not finished
        initialProgressList(result['data']);
        //start interval check
        setTimeout(checkResult, 2000);
      },
      200: function(result){
        if (0 != result['error_code']) {
          $('#create-result').text(result['message']);
          //fail
          return;
        }
        initialProgressList(result['data']);
        finishCreate();
      }
    }
  });
}



function createGuest(request){
  //update form
  $('#button').empty();
  $('#create-panel').empty().removeClass('m10').addClass('m6');
  var disks = new Array();
  request.disks.forEach((size) => {
    disks.push(size / ( 1 << 30));
  });
  var info = versions.get(request.system_version);
  var versionName = info.Name;

  var table = $('<table>').addClass('striped');
  table.append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagComputePool))
    ).append(
      $('<td>').text(request.pool)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagCore))
    ).append(
      $('<td>').text(request.cores)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagMemory))
    ).append(
      $('<td>').text((request.memory / ( 1 << 20 ) ) + ' MiB')
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagDisk))
    ).append(
      $('<td>').text(disks.join(' / ') + ' GiB')
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagSystemVersion))
    ).append(
      $('<td>').text(versionName)
    )
  ).append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagSystem))
    ).append(
      $('<td>').text(request.system)
    )
  );
  if (request.from_image){
    table.append(
      $('<tr>').append(
        $('<td>').text(texts.get(N.TagImage))
      ).append(
        $('<td>').text(request.from_image)
      )
    );
  }
  if (request.auto_start){
    table.append(
      $('<tr>').append(
        $('<td>').text(texts.get(N.TagAutoStart))
      ).append(
        $('<td>').text(texts.get(N.TagEnable))
      )
    );
  }else{
    table.append(
      $('<tr>').append(
        $('<td>').text(texts.get(N.TagAutoStart))
      ).append(
        $('<td>').text(texts.get(N.TagDisable))
      )
    );
  }
  table.append(
    $('<tr>').append(
      $('<td>').text(texts.get(N.TagResult))
    ).append(
      $('<td>').attr('id', 'create-result')
    )
  );
  $('#create-panel').append(table);
  M.AutoInit();

  //begin create
  $.ajax({
    url: '/batch/create_guest/',
    method: "POST",
    dataType: "json",
    data: JSON.stringify(request),
    statusCode: {
      202:function(result){
        //accept
        if (0 != result['error_code']) {
          $('#create-result').text(result['message']);
          return;
        }
        batchID = result['data']['id'];
        //further result
        beginCheckProgress();
      },
      200:function(result){
        //accept
        if (0 != result['error_code']) {
          $('#create-result').text(result['message']);
          return;
        }
      }
    }
  });
}

var selectedImage = "";
var selectedSystem = "linux";

function getCurrentSystem(){
  var currentVersion = $('#version-options').val();
  if (!versions.has(currentVersion)){
    M.toast({html: 'invalid version: ' + currentVersion});
    return
  }
  var info = versions.get(currentVersion);
  return info.System;
}


function onSystemChanged(){
  var currentSystem = getCurrentSystem();
  //linux
  if (currentSystem == selectedSystem){
    return;
  }
  selectedSystem = currentSystem;
  if ('linux' != currentSystem){
    //only linux allowed
    detachGuestOptions();
    return;
  }

  var currentImage = $('#image-options').val();
  if (currentImage){
    attachGuestOptions();
  }else{
    detachGuestOptions();
  }
}

function onImageChanged(){
  var currentSystem = getCurrentSystem();
  if ('linux' != currentSystem){
    //only linux allowed
    selectedImage = $('#image-options').val();
    return;
  }
  var currentImage = $('#image-options').val();
  if (currentImage != selectedImage){
    if ("" == currentImage && "" !=selectedImage){
      detachGuestOptions();
    }else if ("" != currentImage && "" ==selectedImage){
      attachGuestOptions();
    }
    selectedImage = currentImage;
  }
}

function attachGuestOptions(){
  var modules = $("<div>").addClass('row').attr('id', 'module-input').append(
    $('<div>').addClass('input-field').append(
      $('<div>').addClass('col m2').append(
        $('<label>').text(texts.get(N.TagInstalledModule))
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<label>').append(
          $('<input>').attr('type', 'checkbox').attr('name', 'installed_modules').attr('value', 'qemu').addClass('filled-in')
        ).append(
          $('<span>').text('QEMU')
        )
      )
    ).append(
      $('<div>').addClass('col m2').append(
        $('<label>').append(
          $('<input>').attr('type', 'checkbox').attr('name', 'installed_modules').attr('onchange', 'onCIModuleChanged()')
          .attr('id', 'module-cloud-init').attr('value', 'cloud-init').addClass('filled-in')
        ).append(
          $('<span>').text('Cloud-Init')
        )
      )
    )
  );
  $("#confirm_modal").before(modules);
}

function detachGuestOptions(){
  $('#module-input').remove();
  detachCIOptions();
}

function onCIModuleChanged(){
  if ($('#module-cloud-init').is(':checked')){
    attachCIOptions();
  }else{
    detachCIOptions();
  }
}

function attachCIOptions(){
  var ci = $("<div>").addClass('row').attr('id', 'ci-input').append(
    $('<div>').addClass('input-field').append(
      $('<div>').addClass('col m2').append(
        $('<label>').text('Cloud-Init')
      )
    ).append(
      $('<div>').addClass('col m3').append(
        $('<label>').attr('for', 'auth-user').text('Admin Name')
      ).append(
        $('<input>').attr('placeholder', 'root').attr('type', 'text').attr('id', 'auth-user')
      ).append(
        $('<label>').attr('for', 'auth-secret').text('Admin Password')
      ).append(
        $('<input>').attr('placeholder', 'leave blank to generate').attr('type', 'password').attr('id', 'auth-secret')
      ).append(
        $('<label>').attr('for', 'data-path').text('Data Path')
      ).append(
        $('<input>').attr('disabled', 'disabled').attr('type', 'text').attr('id', 'data-path').attr('value', '/opt/data')
      )
    )
  );
  $("#confirm_modal").before(ci);
}

function detachCIOptions(){
  $('#ci-input').remove();
}

function submitCreateRequest() {
    var request = new Object();
    request.name_rule = $('input[name=name_rule]:checked').val();
    request.name_prefix = $('#prefix-name').val();
    //verify name
    var nameRule = new RegExp("[^\\w-]");
    if(request.name_prefix.match(nameRule)){
      if (N.IsChinese()){
        M.toast({html: "前缀仅允许使用字母、数字以及字符'_'和'-'"});
      }else{
        M.toast({html: "Only letters, digits and '-'/'_' allowed in instance prefix"});
      }
      return;
    }

    request.count = parseInt($('#guest-count').val());
    request.owner = N.GetCurrentUser();
    request.group = N.GetCurrentGroup();
    request.pool = $('#pool-options').val();
    request.cores = Number($('input[name=cores]:checked').val());
    request.memory = Number($('input[name=memory]:checked').val());
    var currentVersion = $('#version-options').val();
    if (!versions.has(currentVersion)){
      M.toast({html: 'invalid version: ' + currentVersion});
      return
    }
    request.system_version = currentVersion

    var info = versions.get(currentVersion);
    request.system = info.System;


    const GiB = 1 << 30;
    request.disks = new Array();
    var systemDisk = Number($('#system-disk').val()) * GiB;
    request.disks.push(systemDisk);
    var sourceImage = $('#image-options').val();
    if ('' != sourceImage){
      request.from_image = sourceImage;
      request.modules = new Array();
      $('input[name=installed_modules]:checked').each(function(){
        request.modules.push($(this).val());
      });
      if ($('#module-cloud-init').is(':checked')){
        //Cloud-init enabled
        var ciConfig = new Object();
        ciConfig.admin_name = $('#auth-user').val();
        ciConfig.admin_secret = $('#auth-secret').val();
        ciConfig.data_path = $('#data-path').val();
        request.cloud_init = ciConfig;
      }
    }
    var dataDisk = Number($('#data-disk').val()) * GiB;
    if (0 != dataDisk){
      request.disks.push(dataDisk);
    }
    if ($('#auto_start').prop("checked")){
      request.auto_start = true;
    }else{
      request.auto_start = false;
    }
    {
      var qos = new Object();
      qos.cpu_priority = $('input[name=priority]:checked').val();
      var iops = Number($('#iops').val());
      if(0 != iops){
          qos.write_iops = qos.read_iops = iops;
      }
      const mps = 1 << (20 - 3);
      var inbound = Number($('#inbound').val());
      if(0 != inbound){
        //trans to byte
        qos.receive_speed = inbound * mps;
      }
      var outbound = Number($('#outbound').val());
      if(0 != outbound){
        //trans to byte
        qos.send_speed = outbound * mps;
      }
      request.qos = qos;
    }
    
    N.WriteOperateLog('try create ' + request.count + ' guest(es) in pool ' + request.pool);
    createGuest(request);
}

var originURL, poolName;

function parseQueryString(){
  var url = window.location.search;
  var queryParams = new Map();
  var queryString = url.substring( url.indexOf('?') + 1 );
  if (0 === queryString.length){
    return queryParams;
  }
  var values = queryString.split("&");
  values.forEach((value) => {
    var p = value.split('=');
    queryParams.set(p[0], p[1]);
  });
  return queryParams;
}

$(function(){
  var params = parseQueryString();
  if (params.has('origin')){
    originURL = params.get('origin');
  }
  if (params.has('pool')){
    poolName = params.get('pool');
  }
  initialForm();
});


</script>
</body>
</html>
